package com.caiheng.api.controller.platform;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caiheng.api.constant.ResponseCode;
import com.caiheng.api.entity.active.CommunityActive;
import com.caiheng.api.entity.active.CommunityActiveSign;
import com.caiheng.api.entity.sys.SysDictData;
import com.caiheng.api.entity.wxuser.User;
import com.caiheng.api.service.active.CommunityActiveService;
import com.caiheng.api.service.active.CommunityActiveSignService;
import com.caiheng.api.service.sys.SysDictDataService;
import com.caiheng.api.service.wxuser.UserService;
import com.caiheng.api.util.GsonResultBean;
import com.caiheng.api.util.Tools;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;

/**
 *@Author: ZhouWei
 *@Description:  社区活动 相关接口
 *@Date 2018-05-10
 */
@Component
@RestController
@RequestMapping("/active")//url:模块/资源/{}/细分
public class ActiveController extends BaseController {

    @Resource
    private UserService userService;
    @Resource
    private CommunityActiveService communityActiveService;
    @Resource
    private CommunityActiveSignService communityActiveSignService;
    @Resource
    private SysDictDataService sysDictDataService;

    @Value("${web.imgPrefixOss}")
    private String imgPrefix;//图片地址

    /**
     * 详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/detail")
    public JSONObject detail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "active/detail 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int active_id = jsonRequest.containsKey("active_id") ? jsonRequest.getInt("active_id") : 0;

//            User user = userService.findById(user_id);
//            if(user == null){
//                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
//            }
            CommunityActive active = communityActiveService.findById(active_id);
            if(active != null){

                active.setIsSign(0);
                QueryWrapper<CommunityActiveSign> qw = new QueryWrapper<>();
                qw.eq("active_id", active_id);
                qw.eq("wx_user_id", user_id);
                long count = communityActiveSignService.count(qw);
                if(count > 0){
                    active.setIsSign(1);
                }
                if(StrUtil.isNotEmpty(active.getPreviewImg())){
                    active.setPreviewImg(imgPrefix + active.getPreviewImg());
                }
            }
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",active),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     *  社区活动列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/list")
    public JSONObject list(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String, Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "estate/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int active_type = jsonRequest.containsKey("active_type") ? jsonRequest.getInt("active_type") : -1;
            int pageIndex = jsonRequest.containsKey("pageIndex")&& StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString())  ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize")&& StrUtil.isNotEmpty(jsonRequest.get("pageSize").toString())  ? jsonRequest.getInt("pageSize") : 10;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }

            List<CommunityActive> actives = new ArrayList<>();
            List<SysDictData> activeTypeList = sysDictDataService.selectDictDataList("active_type");
            map.put("activeTypeList", activeTypeList);
            if(CollUtil.isNotEmpty(activeTypeList)){
                actives = communityActiveService.getActivceList(user_id,active_type,pageIndex,pageSize);
                map.put("activeList", actives);
            }

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",actives.size(),map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     * 参与报名
     * @param
     * @throws Exception
     */
    @PostMapping(value="/add/sign")
    public JSONObject addSign(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "active/detail 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int active_id = jsonRequest.containsKey("active_id") ? jsonRequest.getInt("active_id") : 0;
            String realName = jsonRequest.containsKey("real_name") ? jsonRequest.getStr("real_name") : "";
            String phoneNum = jsonRequest.containsKey("phone_num") ? jsonRequest.getStr("phone_num") : "";
            String remark = jsonRequest.containsKey("remark") ? jsonRequest.getStr("remark") : "";
            int signCount = jsonRequest.containsKey("sign_count") ? jsonRequest.getInt("sign_count") : 1;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }
            CommunityActive active = communityActiveService.findById(active_id);
            if(active == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"本活动不存在"),true,true);
            }

            if(signCount > active.getMaxSignCount()){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"已超出本活动的报名上限"),true,true);
            }

            if(active.getBeginTime().getTime() > new Date().getTime()){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"活动未开启"),true,true);
            }
            if(active.getEndTime().getTime() < new Date().getTime()){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"活动已结束"),true,true);
            }

            QueryWrapper<CommunityActiveSign> qw = new QueryWrapper<>();
            qw.eq("active_id", active_id);
            long count = communityActiveSignService.count(qw);
            if(active.getUserCount() <= count){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参与人数已满，谢谢参与！"),true,true);
            }

            CommunityActiveSign sign = new CommunityActiveSign();
            sign.setActiveId(active_id);
            sign.setCreateTime(new Date());
            sign.setState(0);
            sign.setRealName(realName);
            sign.setPhoneNum(phoneNum);
            sign.setWxUserId(user_id);
            sign.setSignCount(signCount);
            sign.setRemark(remark);
            boolean bl = communityActiveSignService.save(sign);
            if(bl){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"参与成功，谢谢参与！"),true,true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参与失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

}
